package cn.jn.lhm.part01;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author lhm 2753914576@qq.com
 * @time 2022/6/14 - 23:26
 **/
@Slf4j
public class TestByteBuffer {
    public static void main(String[] args) {
        // FileChannel
        // 1. 输入输出流
        // 2. RandomAccessFile

        // 获取项目的根目录所在的文件路径
        String file = TestByteBuffer.class.getResource("/").getFile() + "data.txt";

        try (FileChannel channel = new FileInputStream(file).getChannel()) {
            // 准备缓冲区 10个字节
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                // 从channel读取写入buffer
                int len = channel.read(buffer);

                // 如果读取结束则跳出
                if (len == -1) break;

                // 切换到读模式
                buffer.flip();

                // 打印buffer信息
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    log.info("读取到的字节 {}", (char)b);
                }
                // 切换到写模式
                buffer.clear();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
